package ru.ifmo.tanya.core.users;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import ru.ifmo.tanya.db.DataBaseManager;
import ru.ifmo.tanya.util.Pair;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;


public class UserKeeper {

    public static final String SESSION_ID = "session_id";
    private static ConcurrentMap<String, User> authorizedUsers = new ConcurrentHashMap<>();

    public User checkPasswordAndSetCookie(HttpServletRequest request, HttpServletResponse response) {
        String login = request.getParameter("login");
        String pass = request.getParameter("pass");
        List<Pair<User, String>> usersAndPasswords = DataBaseManager.getJdbcTemplate().query("SELECT * FROM users WHERE extension = ?", new ParameterizedRowMapper<Pair<User, String>>() {
            @Override
            public Pair<User, String> mapRow(ResultSet resultSet, int i) throws SQLException {
                return Pair.create(
                        new User(resultSet.getInt("id"), resultSet.getString("name"), UserRole.valueOf(resultSet.getString("role").toUpperCase()), resultSet.getString("extension")),
                        resultSet.getString("password")
                );
            }
        }, login);
        if (!usersAndPasswords.isEmpty()) {
            Pair<User, String> userAndPassword = usersAndPasswords.get(0);
            if (userAndPassword.getSecond().equals(pass)) {
                String sessionUid = UUID.randomUUID().toString();
                response.addCookie(new Cookie(SESSION_ID, sessionUid));
                authorizedUsers.put(sessionUid, userAndPassword.getFirst());
                return userAndPassword.getFirst();
            }
        }
        return null;
    }

    public User extractUser(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        for (final Cookie cookie : cookies) {
            if (SESSION_ID.equals(cookie.getName())) {
                String value = cookie.getValue();
                return authorizedUsers.get(value);
            }
        }

        return null;
    }
}
